package com.fushenlan.epidemicControl.aspect;

import cn.hutool.core.io.IoUtil;
import cn.hutool.http.ContentType;
import cn.hutool.json.JSONUtil;
import com.fushenlan.commons.GeneralResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 全局异常捕获处理
 *
 * @author Administrator
 * @date 2022/4/21 10:11
 */
@RestControllerAdvice
@Slf4j
public class ControllerExceptionAdvice {

    @Autowired
    private HttpServletResponse response;

    @ExceptionHandler(value = Exception.class)
    public void customerException(Exception e) {
        String errorLogKey = String.valueOf(Math.random()).replaceFirst("[.]", "x");
        log.error("【APP】===> An exception occurred：[{}]", errorLogKey, e);
        String msg = JSONUtil.toJsonStr(GeneralResponse.fail("-1", errorLogKey, e.getMessage()));
        //打印
        PrintWriter writer = null;
        try {
            response.setContentType(ContentType.JSON.getValue());
            response.setCharacterEncoding("UTF-8");
            writer = response.getWriter();
            writer.print(msg);
            writer.flush();
        } catch (IOException ex) {
            log.error("Exception msg print", ex);
        } finally {
            IoUtil.close(writer);
        }
    }
}
